/**
 * 腾讯地图路线规划服务（修复版）
 */
export default {
	async getRoute(options) {
		const {
			startPoint,
			endPoint,
			type = 'driving'
		} = options;

		if (!startPoint || !endPoint) {
			throw new Error('缺少起点或终点坐标');
		}

		const key = 'DWLBZ-ZYY63-DF73E-RKK5V-MO3AV-3LBFF';
		const params = {
			from: `${startPoint.lat},${startPoint.lng}`,
			to: `${endPoint.lat},${endPoint.lng}`,
			key
		};

		const url = `https://apis.map.qq.com/ws/direction/v1/${type}/?${this._formatParams(params)}`;

		try {
			const {
				data
			} = await uni.request({
				url
			});

			console.log('API原始响应:', JSON.stringify(data, null, 2));

			if (data.status !== 0) {
				throw new Error(`路线规划失败: ${data.message}`);
			}

			if (!data.result || !data.result.routes || !data.result.routes[0]) {
				throw new Error('未找到可行路线');
			}

			return this._processRouteResponse(data.result, options);
		} catch (error) {
			console.error('获取路线失败:', error);
			throw error;
		}
	},

	_processRouteResponse(result, options) {
		const route = result.routes[0];
		const points = [];

		// 尝试从不同可能的字段获取坐标
		if (route.polyline) {
			console.log('原始polyline类型:', typeof route.polyline);

			if (typeof route.polyline === 'string') {
				// 处理编码字符串
				try {
					const decodedPoints = this._decodePolyline(route.polyline);
					console.log('解码后坐标数量:', decodedPoints.length);
					points.push(...decodedPoints);
				} catch (e) {
					console.error('解码失败:', e);
				}
			} else if (Array.isArray(route.polyline)) {
				// 处理数组格式
				route.polyline.forEach(item => {
					if (typeof item === 'string') {
						try {
							const decoded = this._decodePolyline(item);
							points.push(...decoded);
						} catch (e) {
							console.error('解码分段失败:', e);
						}
					} else if (Array.isArray(item) && item.length === 2) {
						// 直接的坐标点 [lng, lat]
						points.push({
							longitude: item[0],
							latitude: item[1]
						});
					} else if (item.lng && item.lat) {
						// 对象格式的坐标点 { lng, lat }
						points.push({
							longitude: item.lng,
							latitude: item.lat
						});
					} else {
						console.warn('未知格式的坐标项:', item);
					}
				});
			}
		} else if (route.steps && route.steps.length) {
			// 如果polyline不存在，尝试从steps中提取
			console.log('尝试从steps中提取坐标');

			route.steps.forEach(step => {
				if (step.polyline) {
					if (typeof step.polyline === 'string') {
						try {
							const decoded = this._decodePolyline(step.polyline);
							points.push(...decoded);
						} catch (e) {
							console.error('解码step失败:', e);
						}
					} else if (Array.isArray(step.polyline)) {
						step.polyline.forEach(item => {
							if (Array.isArray(item) && item.length === 2) {
								points.push({
									longitude: item[0],
									latitude: item[1]
								});
							}
						});
					}
				}
			});
		}

		console.log('最终解析的坐标点数量:', points.length);

		if (points.length === 0) {
			console.error('未找到任何坐标点！请检查API响应格式:', route);
		}

		return {
			distance: route.distance,
			duration: Math.round(route.duration / 60),
			polyline: [{
				points,
				color: '#007AFF',
				width: 6,
				dottedLine: false
			}],
			startLocation: points[0] || options.startPoint,
			endLocation: points[points.length - 1] || options.endPoint,
			steps: route.steps || []
		};
	},

	_decodePolyline(encoded) {
		if (!encoded || typeof encoded !== 'string') return [];

		const points = [];
		let index = 0;
		let lat = 0;
		let lng = 0;

		while (index < encoded.length) {
			let b, shift = 0,
				result = 0;

			// 解析纬度
			do {
				b = encoded.charCodeAt(index++) - 63;
				result |= (b & 0x1f) << shift;
				shift += 5;
			} while (b >= 0x20);

			const dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
			lat += dlat;

			// 解析经度
			shift = 0;
			result = 0;

			do {
				b = encoded.charCodeAt(index++) - 63;
				result |= (b & 0x1f) << shift;
				shift += 5;
			} while (b >= 0x20);

			const dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
			lng += dlng;

			points.push({
				latitude: lat / 1e5,
				longitude: lng / 1e5
			});
		}

		// 应用增量（如果有多个点）
		if (points.length > 1) {
			for (let i = 1; i < points.length; i++) {
				points[i].latitude += points[i - 1].latitude;
				points[i].longitude += points[i - 1].longitude;
			}
		}

		return points;
	},

	_formatParams(params) {
		return Object.keys(params)
			.map(key => `${key}=${encodeURIComponent(params[key])}`)
			.join('&');
	}
};